/*
 * ttbqt - A teletekst browser
 * http://code.google.com/p/ttbqt
 * Copyright (C) 2011, Kevin van der Vlist
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "Teletext.h"

#include <QDebug>

const QString Teletext::TEXTNAME("Teletext");

/**
 * \short Constructor of the base Teletext object. 
 * 
 * Constructor of the base Teletext object. 
 */

Teletext::Teletext() {

}

Teletext::Teletext(PageInfo *p) {
  pageinfo = p;
  qnam = new QNetworkAccessManager(this);
  QObject::connect(qnam, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
}

/**
 * \short Destructor of the base Teletext object. 
 * 
 * Destructor of the base Teletext object. 
 */

Teletext::~Teletext() {

}

/**
 * Return a pixmap to the current page
 */

void Teletext::getTextPage(int page, int subpage) {
}

/**
 * \short Slot function for a finished download
 * 
 * \param p Pointer to the QNetworkReply
 * 
 * Set the pixpage to the downloaded image. 
 * This function needs to be overridden if the download is not an image. 
 */

void Teletext::downloadFinished(QNetworkReply* reply) {
  qDebug() << "downloadFinished() - url: " << reply->request().url();
  QImage image;
  if (reply->error() == QNetworkReply::NoError) {
    // Valid reply
    image.load(reply, 0);
    if (!image.isNull()) {
      pixpage = new QPixmap(QPixmap::fromImage(image));
      if(pixpage != NULL) {
	pageinfo->setTeletextPage(pixpage);
      }
      qDebug() << "downloadFinished(): OK";
    }
  }
  else {
    // Page not found
      qDebug() << "downloadFinished(): ERR";
  }
  reply->deleteLater();
}

bool Teletext::requestIsRunning() {
  if(reply != NULL) {
    return reply->isRunning();
  } else {
    return false;
  }
}
QString Teletext::getChannelName() {
  return channelname;
}
